﻿using B.S.RbacData.Domain;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using B.S.RbacData.Read.API.Applications.Commands;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.RbacData.Read.API.Applications.CommandHandlters
{
    /// <summary>
    /// 权限列表查询命令处理
    /// </summary>
    public class GetRbacCommandHandlter : IRequestHandler<GetRbacCommand, ApiPaging<PermissionModel>>
    {
        private readonly IBaseRepository<PermissionModel> perRep;

        public GetRbacCommandHandlter(IBaseRepository<PermissionModel> perRep)
        {
            this.perRep = perRep;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public async Task<ApiPaging<PermissionModel>> Handle(GetRbacCommand request, CancellationToken cancellationToken)
        {


            var list = perRep.GetAll().AsNoTracking().Where(x=>x.IsDeleted==false);

            //权限名称的模糊查
            if (!string.IsNullOrEmpty(request.PermissionName))
            {

                list = list.Where(x => x.PermissionName.Contains(request.PermissionName));
            }

            //总条数
            var totalcount = list.Count();
            //总页数
            var totalpage = (int)Math.Ceiling(1.0 * totalcount / request.PageSize);
            //分页结果
            list = list.OrderBy(x => x.ID).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            return new ApiPaging<PermissionModel>
            {
                code = ResultEnumCode.Ok,
                PageData = list.ToList(),
                PageCount = totalpage,
                TotalCount = totalcount,
                message="查询成功"

            };

        }
    }
}
